package com.u.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DownloadFile
 */
@WebServlet("/DownloadFile")
public class DownloadFile extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadFile() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		OutputStream out;
		InputStream in;
		String filename = (String) request.getAttribute("filename");
		System.out.println(filename);
		if(filename == null) {
			return;
		}
		in = getServletContext().getResourceAsStream("/store/" + filename);
		int length = in.available();
		response.setContentType("application/force-download");
		response.setHeader("Content-Length", String.valueOf(length));
		response.setHeader("Content-Disposition", "attachment;filename=\"" +filename);
	
		out = response.getOutputStream();
		int bytesRead = 0;
		byte[] buffer = new byte[512];
		while((bytesRead = in.read(buffer))!=-1) {
			out.write(buffer, 0, bytesRead);
		}
		
		in.close();
		out.close();
	}

}
